<?php


namespace App\Http\Controllers;


use App\Product;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Excel;



class ExcelController extends Controller
{
//$reader->ignoreEmpty();
//or
//在循环遍历导入的数据的时候主动忽略null
//Excel文件导出功能 By Laravel学院
    public function export(){
        Excel::create('订单统计'.date('Y-m-d H_i_s'), function ($excel) {
            $excel->sheet('order', function ($sheet) {
                $sheet->setWidth(array(
                    'A'     => 15,
                    'B'     =>  15,
                    'C'     =>  15,
                    'D'     => 15,
                    'E'     =>  15,
                    'F'     =>  15,
                    'G'     => 15,
                    'H'     =>  25,
                ));
                $sheet->row(1, function($row) {

                    // call cell manipulation methods

                    $row->setBackground('#0000ff');

                });
                $users = Product::orderBy('created_at', 'desc')->with('type')->get(); //要用get()
                $fw='A1:J'.(count($users)+1);

                //$objActSheet->getColumnDimension('B')->setAutoSize(true);

                for($i=0;$i<count($users);$i++)
                {
                    $users[$i]['type_id']=$users[$i]['type']['name'];
                    $users[$i]['image']=null;
                }

                //dd($sheet);
                $sheet->appendRow(['产品ID','产品描述','产品名称','产品分类','产品规格','成本价','销售价','创建时间']);//这里是表头的名称
                foreach($users as $o){ //appendRow是导出一行，要导出数据表就要循环这个

                    $sheet->appendRow([$o->id,(string)$o->describe,$o->product_name,$o->type_id,$o->specifications,$o->cost_price,$o->retail_price,$o->created_at]);//进行循环

                }
                $sheet->cells($fw,function($cells) { //$f是范围。匿名函数设置左对齐

                    $cells->setAlignment('left');

                });
            });
        })->download('xls');  //->download('csv');
    }
    //Excel文件导入功能 By Laravel学院
    public function import(){
        $filePath = 'storage/exports/'.iconv('UTF-8', 'GBK', '学生成绩').'.xls';
        Excel::load($filePath, function($reader) {
            $data = $reader->all();
            dd($data);
        });
    }

}
?>